package com.dhec.ptms.epr.db;

import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dhec.ptms.epr.model.SourceRecord;
import com.ionglobal.db.DBI;
import com.ionglobal.lib.SysException;

public class SourceRecordDB {
	private static final Logger logger = LoggerFactory
			.getLogger(SourceRecordDB.class);

	public SourceRecord findByReportId(DBI dbi, int reportid) {
		SourceRecord bean = null;
		try {
			String sql = "select * from EPR_SourceRecord where reportid="
					+ reportid;
			dbi.execQuery(sql);
			if (dbi.rsNext()) {
				bean = new SourceRecord();
				this.handleData(dbi, bean);
			}
			dbi.rsClose();
		} catch (SysException e) {
			logger.error("EngineerReportDB.list(DBI, Map, int, int) Error!", e);
		}

		return bean;
	}

	public void handleData(DBI dbi, SourceRecord bean) throws SysException {
		bean.setFinishdate(dbi.rsGetDate("finishdate"));
		bean.setHumidity(dbi.rsGetString("humidity"));
		bean.setId(dbi.rsGetInt("id"));
		bean.setModel(dbi.rsGetString("model"));
		bean.setReportid(dbi.rsGetInt("reportid"));
		bean.setRoom(dbi.rsGetString("room"));
		bean.setTableno(dbi.rsGetString("tableno"));
		bean.setTemperature(dbi.rsGetString("temperature"));
		bean.setSourcefile(dbi.rsGetString("sourcefile"));
		bean.setBanci(dbi.rsGetString("banci"));
		bean.setRunintime(dbi.rsGetString("runintime"));
	}

	public boolean insert(SourceRecord bean, DBI dbi) throws SysException {
		String sql ="INSERT INTO EPR_SourceRecord VALUES ("
						+ bean.getId()
						+ ", "
						+ bean.getReportid()
						+ ", '"
						+ dbi.fixSql(bean.getTableno())
						+ "', "
						+ dbi.getInsertDate(bean.getFinishdate())
						+ ", '"
						+ dbi.fixSql(bean.getHumidity())
						+ "', '"
						+ dbi.fixSql(bean.getTemperature())
						+ "', '"
						+ dbi.fixSql(bean.getModel())
						+ "', '"
						+ dbi.fixSql(bean.getRoom()) + "', "
						+(bean.getSourcefile()!=null?"'"+dbi.fixSql(bean.getSourcefile())+"'":"null")+",'"
						+ dbi.fixSql(bean.getBanci())+"', '"+dbi.fixSql(bean.getRunintime())+"')";
		return dbi
				.execute(sql);
	}

	public boolean update(SourceRecord bean, DBI dbi) throws SysException {
		String sql = "UPDATE EPR_SourceRecord SET tableno = '"
				+ dbi.fixSql(bean.getTableno()) + "', finishdate = "
				+ dbi.getInsertDate(bean.getFinishdate()) + ", humidity = '"
				+ dbi.fixSql(bean.getHumidity()) + "', temperature = '"
				+ dbi.fixSql(bean.getTemperature()) + "', model = '"
				+ dbi.fixSql(bean.getModel()) + "', room = '"
				+ dbi.fixSql(bean.getRoom()) + "', sourcefile = "
				+(bean.getSourcefile()!=null?"'"+dbi.fixSql(bean.getSourcefile())+"'":"null")+", banci='"
				+dbi.fixSql(bean.getBanci())+"', runintime='"+dbi.fixSql(bean.getRunintime())+"'"
				+" WHERE id =" + bean.getId();
		return dbi.execute(sql);
	}
	
}
